/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csci311;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 *
 * @author Elveslab
 */
public class Searcher {

    public static ArrayList<ArrayList> runQuery(String queryText, File INDEX_DIR, String FIELD_CONTENTS, String FIELD_PATH, String FIELD_FILENAME) throws ParseException, CorruptIndexException, IOException {
        String querystr = queryText;
        ArrayList<ArrayList> arrayListDocument = new ArrayList();
        if (queryText.length() > 0) {
            Query q = new QueryParser(Version.LUCENE_34, FIELD_CONTENTS, new StandardAnalyzer(Version.LUCENE_34)).parse(querystr);

            int hitsPerPage = 100;
            IndexSearcher searcher = new IndexSearcher(FSDirectory.open(INDEX_DIR), true);
            TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
            searcher.search(q, collector);
            ScoreDoc[] hits = collector.topDocs().scoreDocs;

            ArrayList<String> arrayListPath = new ArrayList();
            ArrayList<String> arrayListFilename = new ArrayList();
            for (int i = 0; i < hits.length; ++i) {
                int docId = hits[i].doc;
                Document d = searcher.doc(docId);
                arrayListPath.add(d.get(FIELD_PATH));
                arrayListFilename.add(d.get(FIELD_FILENAME));
            }
            arrayListDocument.add(arrayListFilename);
            arrayListDocument.add(arrayListPath);
        }
        else
        {
            ArrayList<String> emptyArrayList = new ArrayList();
            emptyArrayList.add("");
            arrayListDocument.add(emptyArrayList);
            arrayListDocument.add(emptyArrayList);
        }
        return arrayListDocument;
    }
}
